<?php

namespace App\Console\Commands\Image;

use App\Models\Digital;
use App\Services\Http;
use App\Services\LogTrait;
use function Couchbase\basicDecoderV1;
use Illuminate\Console\Command;

class Mt extends Command
{
    use LogTrait;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'image:mt {start=1} {end=173}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '美图吧图片';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @throws \Exception
     * @return mixed
     */
    public function handle()
    {
        try{
            $this->logName = $this->signature;
            $http = Http::getInstance();

            $start = $this->argument('start');
            $end   = $this->argument('end');
            for ( $page = $start; $page <= $end; $page++ ) {
                $this->logWrite('start page->'.$page.'...');

                $response = $http->request('get', 'http://www.meituba.com/xinggan/list8'.$page.'.html');
                $content = $response->getBody()->getContents();

                preg_match_all('/<a title="(.*)" href="(.*)" target="_blank">/', $content, $match);
                $titles = $match[1];
                $urls = $match[2];

                preg_match_all('/<div class="items_likes">浏览次数：(.*)次.*共(.*)张<\/div>/', $content, $match);
                $views = $match[1];
                $nums = $match[2];

                foreach ($urls as $key => $url) {
                    $title = $titles[$key];
                    $num = $nums[$key] ?? 20;
                    $view = $views[$key];

                    for ($i = 2; $i <= $num; $i++) {
                        try {
                            $newUrl = str_replace('.html', '_' . $i . '.html', $url);
                            $response = $http->get($newUrl);
                            $content = $response->getBody()->getContents();
                            preg_match('/.*<img alt="' . $title . '" src="(.*?)".*>/', $content, $match);
                        }catch (\Exception $e){
                            $this->logWrite($newUrl);
                            $this->logWrite($e->getMessage());
                            continue;
                        }

                        if( !isset($match[1]) ) {
                            continue;
                        }

                        $image = $match[1];
                        $insert = [
                            'title' => '穿衣风格搭配大全',//$title,
                            'url' => $image,
                            'first_image' => $image,
                            'view' => $view,
                            'source' => 4,
                            'type' => 3,
                        ];
                        $this->dataToDb($insert);
                        $this->logWrite(json_encode($insert, JSON_UNESCAPED_UNICODE));
                    }
                }
            }


        }catch (\Exception $e){
            $this->logWrite($e->getMessage());
            $this->logWrite($e->getTraceAsString());
        }
    }

    /**
     * @author Haohuang
     * @email  huanghao1054@gmail.com
     * @since   2019/9/10
     * @throws \Exception
     * @param $data
     */
    public function dataToDb($data)
    {
        Digital::query()->updateOrCreate([
            'url' => $data['url']
        ], $data);
    }

}
